<template>
    <el-dialog :visible.sync="visible"  :close-on-click-modal="false"  width="95%"
               :close-on-press-escape="false" center>
        <span slot="title" style="font-size: larger; font-weight: bold">合同详情</span>
        <!--        <d2-container>-->
        <!--        <template slot="header">-->
        <!--        </template>-->
        <el-divider/>
        <el-tag type="success" style="margin-bottom: 10px; font-size: large; font-weight: bold;">合同信息列表:</el-tag>
        <el-table
                size="mini"
                v-loading="dataListLoading"
                :data="dataList"
                border
                stripe
                style="width: 100%;">
            <el-table-column type="index" header-align="center" align="center" width="50"/>
            <el-table-column prop="templateName" :label="$t('contractDetail.templateName')" header-align="center" align="center"/>
            <el-table-column prop="status" :label="$t('contractDetail.status')" header-align="center" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.status === 0" size="mini" type="info">{{ $t('contractDetail.status0')}}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === 1" size="mini" type="warning">{{$t('contractDetail.status1') }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === 2" size="mini">{{ $t('contractDetail.status2') }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.status === 3" size="mini" type="success">{{$t('contractDetail.status3') }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" :label="$t('createTime')" sortable="custom" header-align="center"
                             align="center" width="180"/>
            <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="180">
                <template slot-scope="scope">
                    <el-button v-hasPermi="['sys:contract:browse']" v-if="scope.row.status > 0" type="text"
                               size="mini" @click="detailContract(scope.row)">{{ $t('look') }}
                    </el-button>
                    <el-button v-hasPermi="['sys:contract:browse']" v-if="scope.row.status > 0" type="text"
                               size="mini" @click="toBrowse(scope.row)">{{ $t('browse') }}
                    </el-button>
                    <el-button v-hasPermi="['sys:contract:delete']" v-if="scope.row.status === 0" type="text"
                               size="mini" @click="deleteHandle(scope.row.id)">{{ $t('delete') }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <contract-detail :contractDetailData="contractDetailData" ref="contractDetail"></contract-detail>

        <el-divider></el-divider>
        <el-tag type="primary" style="margin-bottom: 10px; font-size: large; font-weight: bold;">合同签署者列表:</el-tag>
        <el-table
                size="mini"
                v-loading="contractSignerLoading"
                :data="contractSignerList"
                border
                stripe
                style="width: 100%;">
            <el-table-column type="index" header-align="center" align="center" width="50"/>
            <el-table-column prop="name" :label="$t('contractSigner.name')" header-align="center" align="center"
                             show-overflow-tooltip/>
            <el-table-column prop="identity" :label="$t('contractSigner.identity')" header-align="center"
                             align="center"/>
            <el-table-column prop="mobile" :label="$t('contractSigner.mobile')" header-align="center"
                             align="center"/>
            <el-table-column prop="realnameStatus" :label="$t('contractSigner.realnameStatus')"
                             header-align="center" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.realnameStatus === 0 && scope.row.partType !== 1" size="mini"
                            type="warn">未认证
                    </el-tag>
                    <el-tag v-else-if="scope.row.realnameStatus === 1 || scope.row.partType === 1" size="mini"
                            type="success">已认证
                    </el-tag>
                    <el-tag v-else-if="scope.row.realnameStatus === 2" size="mini" type="danger">认证失败</el-tag>
                    <el-tag v-else-if="scope.row.realnameStatus === 3" size="mini" type="danger">银行卡四要素认证失败</el-tag>
                    <el-tag v-else-if="scope.row.realnameStatus === 4" size="mini" type="danger">手机号三要素认证失败</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="partType" :label="$t('contractSigner.partType')" header-align="center"
                             align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.partType === 1" size="mini">企业</el-tag>
                    <el-tag v-else-if="scope.row.partType === 2" size="mini" type="danger">个人</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="partName" :label="$t('contractSigner.partName')" header-align="center"
                             align="center"/>
            <el-table-column prop="signStatus" :label="$t('contractSigner.signStatus')" header-align="center"
                             align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.signStatus === 0" size="mini" type="danger">未签署</el-tag>
                    <el-tag v-else-if="scope.row.signStatus === 1" size="mini" type="success">已签署</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="signTime" :label="$t('contractSigner.signTime')" header-align="center"
                             align="center"/>
            <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="180">
                <template slot-scope="scope">
                    <el-popconfirm
                            v-hasPermi="['sys:contract:browse']"
                            v-if="scope.row.partType === 2 && showRepush && dataForm.status === 3 && scope.row.signStatus === 0"
                            @onConfirm="repushContractUrl(scope.row.id)"
                            title="确定重新推送合同签署链接？">
                        <el-button type="text" size="mini" slot="reference">{{ $t('contractSigner.repush') }}
                        </el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!--        <el-pagination-->
        <!--                slot="footer"-->
        <!--                :current-page="page"-->
        <!--                :page-sizes="[10, 20, 50, 100]"-->
        <!--                :page-size="limit"-->
        <!--                :total="total"-->
        <!--                layout="total, sizes, prev, pager, next, jumper"-->
        <!--                @size-change="pageSizeChangeHandle"-->
        <!--                @current-change="pageCurrentChangeHandle">-->
        <!--        </el-pagination>-->
        <el-divider></el-divider>

        <el-row :gutter="20" style="margin-bottom: 10px; ">
            <el-col :span="6">
                <el-tag type="warning" style="margin-bottom: 10px; font-size: large; font-weight: bold;">合同资料列表:
                </el-tag>
            </el-col>
            <el-col :span="6" :offset="12" style="align-items: end; text-align: end;">
                <el-button v-hasPermi="['sys:contract:uploadDatum']" v-if="dataForm.status === 4" type="primary"
                           @click="addOrUpdateHandle()" size="small" style="font-size: 16px; font-weight: bold;">
                    上传资料
                </el-button>
            </el-col>
        </el-row>
        <el-table
                size="mini"
                v-loading="contractDataListLoading"
                :data="contractDatumList"
                border
                stripe
                style="width: 100%;">
            <el-table-column type="index" header-align="center" align="center" width="50"/>
            <el-table-column prop="datumType" :label="$t('contractDatum.datumType')" header-align="center"
                             align="center"/>
            <el-table-column prop="fileName" :label="$t('contractDatum.fileName')" header-align="center"
                             align="center"/>
            <!--            <el-table-column prop="type" :label="$t('lawsuitDatum.type')" header-align="center" align="center"/>-->
            <el-table-column prop="type" :label="$t('contractDatum.type')" header-align="center" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.type === 0" size="mini" type="danger">{{ $t('contractDatum.type0') }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.type === 1" size="mini" type="warning">{{ $t('contractDatum.type1')
                        }}
                    </el-tag>
                    <el-tag v-else-if="scope.row.type === 2" size="mini" type="success">{{ $t('contractDatum.type2')
                        }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" :label="$t('createTime')" sortable="custom" header-align="center"
                             align="center" width="180"/>
            <el-table-column prop="remark" :label="$t('remark')" header-align="center" align="center"/>
            <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150">
                <template slot-scope="scope">
                    <el-button   v-hasPermi="['sys:contract:downloadDatum']" type="text" size="mini"
                               @click="detailHandle(scope.row)">{{ $t('downloadDatum') }}
                    </el-button>
                    <el-button  v-hasPermi="['sys:contract:deleteDatum']" type="text" size="mini"
                               @click="deleteDatumHandle(scope.row.id)">{{ $t('delete') }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
                slot="footer"
                :current-page="contractDatumParams.current"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="contractDatumParams.size"
                :total="contractDatumTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="pageSizeDatumChangeHandle"
                @current-change="pageCurrentDatumChangeHandle">
        </el-pagination>

        <!--合同资料上传-->
        <add-or-update v-if="addOrUpdateVisible" :contract-id="dataForm.contractId" ref="addOrUpdate"
                       @refreshDataList="getContractDatumList"/>

        <!--        </d2-container>-->
    </el-dialog>
</template>

<script>
    import {mapMutations} from 'vuex'
    import mixinViewModule from '@/mixins/view-module'
    import {moduleRoutes} from '@/router'
    import contractDetail from './contract-detail'
    import Template from './template'
    import AddOrUpdate from './contract-datum-add-or-update'

    /* 合同列表 */
    export default {
        components: {AddOrUpdate,Template, contractDetail},
        mixins: [mixinViewModule],
        data() {
            return {
                mixinViewModuleOptions: {
                    deleteURL: '/manager/contract/deleteDetail',
                    deleteIsBatch: true
                },
                statusOptions: [{// （0草稿1合同文件已生成 2上上签签署链接已推送3客户签署完成）
                    label: '草稿',
                    value: 0
                }, {
                    label: '合同文件已生成',
                    value: 1
                }, {
                    label: '上上签签署链接已推送',
                    value: 2
                }, {
                    label: '客户签署完成',
                    value: 3
                }],
                visible: false,
                dataList: [], // 数据列表
                dataListLoading: false, // 数据列表，loading状态
                contractDatumList: [],
                contractDataListLoading: false,
                dataForm: {
                    contractId: 0,
                    status: 0
                },
                queryItems: [
                    {
                        field: 'contractId',
                        as: 'EQ',
                        value: ''
                    },
                    {
                        field: 'status',
                        as: 'EQ',
                        value: ''
                    }
                ],
                contractDatumTotal: 0,
                contractDatumDeleteURL: '/manager/contractDatum/delete',
                contractDatumParams: {
                    order: 'ASC',
                    orderField: 'createTime',
                    current: 1,
                    size: 10,
                    queryItems: ''
                },
                contractDatumQueryItems: [{
                    field: 'contractId',
                    as: 'EQ',
                    value: ''
                }],
                addOrUpdateVisible: false,
                order: 'ASC',
                orderField: 'createTime',
                contractDetailData: null,
                contractSignerLoading: false,
                contractSignerList: [],
                showRepush: false,
                repushVisible: false
            }
        },
        props: {
            parentId: {
                type: Number
            },
            status: {
                type: Number
            }
        },
        methods: {
            init: function () {
                this.visible = true
                this.dataForm.contractId = this.parentId;
                this.dataForm.status = this.status;

                this.contractDatumQueryItems[0].value = this.parentId
                this.getContractDatumList()
                this.getContractSigner()
                this.getDataList();
            },
            ...mapMutations('d2admin/page', {
                d2adminPagePoolPush: 'push'
            }),
            getContractSigner: function () {
                let that = this
                this.$http.get('/manager/contract/getSigners', {contractId: this.dataForm.contractId}).then(res => {
                    that.contractSignerList = res.data
                }).catch(() => {
                })
            },
            getDataList: function () {
                let that = this
                if(this.dataForm.contractId === 0){
                  return;
                }
                this.$http.get('/manager/contract/getFlowContractList', this.dataForm).then(res => {
                    that.dataList = res.data
                    let flag = true
                    for (let i in that.dataList) {
                        if (that.dataList[i].status && that.dataList[i].status !== 2) {
                            flag = false
                            break
                        }
                    }
                    this.showRepush = flag
                }).catch(() => {
                })
            },
            detailContract: function (row) {
                this.contractDetailData = row
                this.$nextTick(() => {
                    this.$refs.contractDetail.init()
                })
            },

            // 预览已签署成功的在线合同信息
            toBrowse: function (row) {
                this.visible = false; //解决弹出蒙层不消失的问题
                if (row.status === 1) {
                    var routeName = 'html'

                    var route = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
                    if (route) {
                        route.meta.title = '合同浏览'
                        return this.$router.push({
                            name: route.name,
                            params: {'url': process.env.VUE_APP_IMG + row.pdfPath, 'title': '合同浏览'}
                        })
                    }
                    // 否则: 添加并全局变量保存, 再跳转
                    route = {
                        path: routeName,
                        component: () => import('@/views/tool/frame/html'),
                        name: routeName,
                        meta: {
                            ...window.SITE_CONFIG['contentTabDefault'],
                            menuId: this.$route.meta.menuId,
                            title: '合同浏览'
                        }
                    }
                    this.$router.addRoutes([
                        {
                            ...moduleRoutes,
                            name: `main-dynamic__${route.name}`,
                            children: [route]
                        }
                    ])
                    window.SITE_CONFIG['dynamicRoutes'].push(route)
                    this.d2adminPagePoolPush(route)
                    this.$router.push({
                        name: route.name,
                        params: {'url': process.env.VUE_APP_IMG + row.pdfPath, 'title': '合同浏览'}
                    })
                } else if (row.status === 2 || row.status === 3) {
                    let params = {
                        contractId: row.id
                    }
                    this.$http.get('/manager/contract/getContractPreviewUrl', params).then(res => {
                        if (res !== undefined && res !== '') {
                            var routeName = 'html'
                            var route = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
                            if (route) {
                                route.meta.title = '合同浏览'
                                return this.$router.push({name: route.name, params: {'url': res, 'title': '合同浏览'}})
                            }
                            // 否则: 添加并全局变量保存, 再跳转
                            route = {
                                path: routeName,
                                component: () => import('@/views/tool/frame/html'),
                                name: routeName,
                                meta: {
                                    ...window.SITE_CONFIG['contentTabDefault'],
                                    menuId: this.$route.meta.menuId,
                                    title: '合同浏览'
                                }
                            }
                            this.$router.addRoutes([
                                {
                                    ...moduleRoutes,
                                    name: `main-dynamic__${route.name}`,
                                    children: [route]
                                }
                            ])
                            window.SITE_CONFIG['dynamicRoutes'].push(route)
                            this.d2adminPagePoolPush(route)
                            this.$router.push({name: route.name, params: {'url': res, 'title': '合同浏览'}})
                        }
                    }).catch(() => {
                    })
                }
            },
            dateFormat: function (row, column) {
                const dateStr = row[column.property]
                if (dateStr != null) {
                    const dateMat = new Date(dateStr)
                    const year = dateMat.getFullYear()
                    const month = dateMat.getMonth() + 1
                    const day = dateMat.getDate()
                    const hh = dateMat.getHours()
                    const mm = dateMat.getMinutes()
                    const ss = dateMat.getSeconds()
                    // const timeFormat = year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
                    // const timeFormat = year + "-" + month + "-" + day;
                    let timeFormat = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day)
                    return timeFormat
                }
            },

            getContractDatumList: function () {
                let that = this
                this.contractDatumParams.queryItems = this.createQueryParams(this.contractDatumQueryItems)
                this.$http.get('/manager/contractDatum/page', this.contractDatumParams).then(res => {
                    that.contractDataListLoading = false
                    that.contractDatumList = res.records
                    that.contractDatumTotal = res.total
                }).catch(() => {
                })
            },

            // 新增 / 修改
            addOrUpdateHandle(id) {
                this.addOrUpdateVisible = true;
                this.contractId = this.dataForm.contractId;
                this.$nextTick(() => {
                    this.$refs.addOrUpdate.dataForm.contractId = this.contractId;
                    this.$refs.addOrUpdate.init()
                })
            },

            // 分页, 每页条数
            pageSizeDatumChangeHandle(val) {
                this.contractDatumParams.current = 1
                this.contractDatumParams.current = val
                this.getContractDatumList()
            },
            // 分页, 当前页
            pageCurrentDatumChangeHandle(val) {
                this.contractDatumParams.current = val
                this.getContractDatumList()
            },

            // 查询条件构造器
            createQueryParams(queryItems) {
                let queryParams = ''
                if (queryItems.length > 0) {
                    for (let i = 0; i < queryItems.length; i++) {
                        let queryItem = queryItems[i]
                        queryParams = queryParams + queryItem.field + ',' + queryItem.as + ',' + queryItem.value + ';'
                    }
                }
                return queryParams
            },

            detailHandle: function (row) {
                let href = row.ossFilePath
                window.open(href, '_blank')
            },

            deleteDatumHandle: function (id) {
                this.$confirm(this.$t('prompt.info', {'handle': this.$t('delete')}), this.$t('prompt.title'), {
                    confirmButtonText: this.$t('confirm'),
                    cancelButtonText: this.$t('cancel'),
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete(
                        `${this.contractDatumDeleteURL}${this.mixinViewModuleOptions.deleteIsBatch ? '' : '/' + id}`,
                        this.mixinViewModuleOptions.deleteIsBatch ? {
                            'data': id ? [id] : this.dataListSelections.map(item => item[this.mixinViewModuleOptions.deleteIsBatchKey])
                        } : {}
                    ).then(res => {
                        this.$message({
                            message: this.$t('prompt.success'),
                            type: 'success',
                            duration: 500,
                            onClose: () => {
                                this.getContractDatumList()
                            }
                        })
                    }).catch(() => {
                    })
                }).catch(() => {
                })
            },
            repushContractUrl: function (customerId) {
                this.$http.get('/manager/contract/repushContractUrl', {
                    contractId: this.dataForm.contractId,
                    customerId: customerId
                }).then(res => {
                    if (res.code === 100) {
                        this.$message.alert('推送成功')
                    } else {
                        this.$message.error('推送失败，原因：' + res.msg)
                    }
                }).catch(() => {
                })
            }

        },
        mounted: function () {

        }

    }
</script>
